package com.lancoo.answer.view.fragment.listenmatch

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import com.lancoo.answer.R
import com.lancoo.answer.component.InteractWebView
import com.lancoo.answer.databinding.EvFragmentListenMatchBinding
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.TaskState
import com.lancoo.answer.model.bean.EvOptionBean
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.model.entity.TaskControlBean
import com.lancoo.answer.view.base.BaseVMFragment
import com.lancoo.answer.view.fragment.cloze.ClozeChildFragment
import com.lancoo.answer.view.fragment.option.SingleOptionFragment

/**
 * dadong 2020 05/18
 * 听力综合：听录音填表格信息
 * 小题抽题
 */
class ListenMatchAnswerFragment : BaseVMFragment<EvFragmentListenMatchBinding>() {
    private val TAG = "ListenMatchAnswerFragment"
    private lateinit var ques: Ques
    private var typeIndex = 0
    private var quesIndex = 0
    private var childIndex = 0
    private var defaultLoadIndex = 0
    private var itemSortIndex: String = "" //当前选择的序号
    private lateinit var clozeChildFragment: ClozeChildFragment

    companion object {
        fun loadFragment(
            typeIndex: Int,
            quesIndex: Int,
            childIndex: Int,
            defaultLoadIndex: Int
        ): Fragment? {
            val mBundle = Bundle()
            mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex)
            mBundle.putInt(AnswerConstant.KEY_QUESINDEX, quesIndex)
            mBundle.putInt(AnswerConstant.KEY_CHILDINDEX, childIndex)
            mBundle.putInt(AnswerConstant.KEY_ITEMINDEX, defaultLoadIndex)
            val listenMatchAnswerFragment = ListenMatchAnswerFragment()
            listenMatchAnswerFragment.arguments = mBundle
            return listenMatchAnswerFragment
        }
    }

    override fun initView(view: View) {
    }

    override fun getLayoutId(): Int {
        return R.layout.ev_fragment_listen_match
    }

    override fun initData() {
        if (ConstantBean.constantExamBean == null) {
            return
        }
        val kindBeanList = ConstantBean.constantExamBean!!.TypeList
        typeIndex = requireArguments().getInt(AnswerConstant.KEY_TYPEINDEX)
        quesIndex = requireArguments().getInt(AnswerConstant.KEY_QUESINDEX)
        childIndex = requireArguments().getInt(AnswerConstant.KEY_CHILDINDEX)
        defaultLoadIndex = requireArguments().getInt(AnswerConstant.KEY_ITEMINDEX)
        Log.e("听力匹配", "loadChildIndex:" + defaultLoadIndex + "childIndex:" + childIndex)
        ques = kindBeanList!![typeIndex].QuesList!![quesIndex]
        if (defaultLoadIndex < 0 || defaultLoadIndex >= ques.ChildList!![childIndex].ItemList!!.size) {
            itemSortIndex = ques.ChildList!![childIndex].ItemList!![0].ItemSortIndex!! //好像没啥用
        } else {
            itemSortIndex =
                ques.ChildList!![childIndex].ItemList!![defaultLoadIndex].ItemSortIndex!!
        }
        initAnswer()
        setInteractWebView()
    }

    //小题抽题
    private fun initAnswer() {
        clozeChildFragment =
            ClozeChildFragment.loadFragment(
                typeIndex,
                quesIndex,
                defaultLoadIndex
            ) as ClozeChildFragment
        if (ConstantBean.taskState != TaskState.ORIGINAL) {
            clozeChildFragment.setChooseCallback(object : SingleOptionFragment.ChooseCallback {
                override fun clickCallback(item: EvOptionBean) {
                    val position = getRealIndex()
                    ques.ChildList!![position].ItemList!![0].StuAnswer = item.OptionIndex
                    wvLoadUrl(itemSortIndex)
                    itemSortIndex = (itemSortIndex.toInt() + 1).toString()
                    dealOverSize()
                    clozeChildFragment.nextChildAsk()
                }
            })
        }
        clozeChildFragment.setPageChangeCallback(object : ClozeChildFragment.PageChangeCallback {
            override fun callback(position: Int) {
                itemSortIndex = ques.ChildList!![position].ItemList!![0].ItemSortIndex!!
                wvLoadUrl(itemSortIndex)
            }
        })
        childFragmentManager
            .beginTransaction()
            .replace(mBinding.flAnswer.id, clozeChildFragment!!, TAG)
            .commit()
    }

    //加载题干
    private fun setInteractWebView() {
        val body = if (ques.QuesBody.isNullOrEmpty()) {
            ques.ChildList!![childIndex].ChildAsk
        } else {
            ques.QuesBody
        }
        mBinding.interactWv.setIsIndentation(ques.IsIndentQuesBody)
        mBinding.interactWv.setQues(ques)
        mBinding.interactWv.initWebView(
            requireActivity(),
            body!!,
            object : InteractWebView.Callback {
                override fun finishCallback() {
                    wvLoadUrl(itemSortIndex)
                }

                override fun clickCallback(position: String) {
                    itemSortIndex = position
                    wvLoadUrl(position)
                    clozeChildFragment.nextChildAsk(getRealIndex())
                    adjustFontSize()
                }
            }
        )
    }

    //获取序号在ItemList 中的位置
    fun getRealIndex(): Int {
        ques.ChildList!!.forEachIndexed { index, item ->
            if (item.ItemList!![0].ItemSortIndex == itemSortIndex) {
                return index
            }
        }
        return 0
    }

    //处理itemSortIndex超过范围的情况
    fun dealOverSize() {
        val size = ques.ChildList!!.size
        val maxIndex = ques.ChildList!![size - 1].ItemList!![0].ItemSortIndex!!
        if (itemSortIndex.toInt() > maxIndex.toInt()) {
            itemSortIndex = maxIndex
        }
    }

    //答题点下划线，高亮等等绘制
    private fun wvLoadUrl(position: String = "-1") {
        mBinding.interactWv.scrollPosition(position)
        if (ConstantBean.taskState != TaskState.ORIGINAL) {
            ques.ChildList!!.forEach {
                mBinding.interactWv.loadUrl(
                    it.ItemList!![0],
                    position == it.ItemList!![0].ItemSortIndex.toString()
                )
            }
        } else {
            ques.ChildList!!.forEach {
                mBinding.interactWv.loadOriginUrl(
                    it.ItemList!![0],
                    position == it.ItemList!![0].ItemSortIndex.toString(),
                    true
                )
            }
        }
    }

    /**
     * 跳转到指定小题
     * @param childIndex 小题序号
     */
    fun jumpToAimChildFragment(childIndex: Int) {
        if (childFragmentManager != null &&
            mBinding != null
        ) {
            val fragment = childFragmentManager.findFragmentByTag(TAG)
            if (fragment is ClozeChildFragment) {
                fragment.setCurrentItem(childIndex)
            }
        }
    }

    fun adjustFontSize() {
        if (mBinding.interactWv != null) {
            mBinding.interactWv.setFontSize()
        }
        clozeChildFragment.adjustFontSize()
    }

    fun markQuestion() {
        var isShow = 0
        ques.ChildList!!.forEachIndexed { index, child ->
            child.ItemList!!.forEachIndexed { itemIndex, item ->
                if (item.ItemSortIndex == itemSortIndex) {
                    isShow = if (item.itemMark) { //
                        0
                    } else {
                        1
                    }
                    item.itemMark = !item.itemMark
                }
            }
        }
        val flagIndex = "znbkflag${itemSortIndex}"
        mBinding.interactWv.showFlag(flagIndex, isShow)
    }
}